﻿// Copyright (c) egmkang wang. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace XServer.Grains
{
    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Orleans;
    using Orleans.Concurrency;
    using SDK;
    using GrainInterfaces;

    [Reentrant]
    public class ServerGrain : Grain, IServerGrain
    {
        Dictionary<long, long> onlinePlayers = new Dictionary<long, long>();

        public Task<int> GetPlayerCount()
        {
            return Task.FromResult(onlinePlayers.Count);
        }

        public Task<int> GetOnlinePlayerCount()
        {
            var sec = Platform.GetSeconds() - 60;
            int count = 0;
            foreach (var item in this.onlinePlayers)
            {
                count += item.Value >= sec ? 1 : 0;
            }
            return Task.FromResult(count);
        }

        public Task PlayerOnline(long playerID)
        {
            if (!this.onlinePlayers.ContainsKey(playerID))
            {
                this.onlinePlayers.Add(playerID, 0);
            }
            this.onlinePlayers[playerID] = Platform.GetSeconds();
            return TaskDone.Done;
        }

        public Task PlayerOffline(long playerID)
        {
            this.onlinePlayers.Remove(playerID);
            return TaskDone.Done;
        }
    }
}
